<template>
  <view class="edit-container">
    <scroll-view class="form-content" scroll-y>
      <!-- 基础信息 -->
      <view class="form-card">
        <view class="section-title">基础信息</view>
        
        <view class="form-item">
          <text class="item-label">负责人姓名</text>
          <input 
            v-model="formData.principal"
            placeholder="请输入负责人姓名"
            class="form-input"
          />
        </view>

        <view class="form-item">
          <text class="item-label">身份证号码</text>
          <input 
            v-model="formData.idNumber"
            placeholder="请输入身份证号码"
            class="form-input"
            type="idcard"
          />
        </view>

        <view class="form-item">
          <text class="item-label">联系电话</text>
          <view class="input-group">
            <input
              v-model="formData.phone"
              placeholder="请输入手机号码"
              class="form-input"
              type="number"
            />
            <button 
              class="sms-btn"
              :disabled="smsDisabled"
              @click="getSmsCode"
            >
              {{ smsText }}
            </button>
          </view>
        </view>
      </view>

      <!-- 经营信息 -->
      <view class="form-card">
        <view class="section-title">经营信息</view>
        
        <view class="form-item">
          <text class="item-label">店铺名称</text>
          <input 
            v-model="formData.shopName"
            placeholder="请输入店铺名称"
            class="form-input"
          />
        </view>

        <view class="form-item">
          <text class="item-label">营业执照号</text>
          <input 
            v-model="formData.licenseNo"
            placeholder="请输入营业执照编号"
            class="form-input"
          />
        </view>

        <view class="form-item">
          <text class="item-label">经营区域</text>
          <picker 
            mode="region" 
            @change="handleRegionChange"
            class="form-input"
          >
            <text>{{ formData.region.join(' ') || '请选择所在地区' }}</text>
          </picker>
        </view>

        <view class="form-item">
          <text class="item-label">详细地址</text>
          <input 
            v-model="formData.address"
            placeholder="请输入详细地址"
            class="form-input"
          />
        </view>

        <view class="form-item">
          <text class="item-label">商家介绍</text>
          <textarea
            v-model="formData.description"
            placeholder="请输入商家简介（200字以内）"
            class="form-textarea"
            maxlength="200"
          />
          <text class="word-count">{{ formData.description.length }}/200</text>
        </view>
      </view>

      <!-- 证照上传 -->
      <view class="form-card">
        <view class="section-title">证照信息</view>
        
        <view class="upload-grid">
          <!-- 身份证人像面 -->
          <view class="upload-item">
            <text class="upload-label">身份证人像面</text>
            <view class="upload-box" @click="uploadFile('idCardFront')">
              <image 
                v-if="formData.idCardFront" 
                :src="formData.idCardFront" 
                class="preview-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="48" :color="isModified ? '#007AFF' : '#999'" />
              </view>
              <view 
                v-if="formData.idCardFront" 
                class="delete-icon"
                @click.stop="formData.idCardFront = ''"
              >
                <uni-icons type="close" size="20" color="#fff" />
              </view>
            </view>
          </view>

          <!-- 身份证国徽面 -->
          <view class="upload-item">
            <text class="upload-label">身份证国徽面</text>
            <view class="upload-box" @click="uploadFile('idCardBack')">
              <image 
                v-if="formData.idCardBack" 
                :src="formData.idCardBack" 
                class="preview-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="48" :color="isModified ? '#007AFF' : '#999'" />
              </view>
              <view 
                v-if="formData.idCardBack" 
                class="delete-icon"
                @click.stop="formData.idCardBack = ''"
              >
                <uni-icons type="close" size="20" color="#fff" />
              </view>
            </view>
          </view>

          <!-- 营业执照 -->
          <view class="upload-item">
            <text class="upload-label">营业执照</text>
            <view class="upload-box" @click="uploadFile('licenseImage')">
              <image 
                v-if="formData.licenseImage" 
                :src="formData.licenseImage" 
                class="preview-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="48" :color="isModified ? '#007AFF' : '#999'" />
              </view>
              <view 
                v-if="formData.licenseImage" 
                class="delete-icon"
                @click.stop="formData.licenseImage = ''"
              >
                <uni-icons type="close" size="20" color="#fff" />
              </view>
            </view>
          </view>

          <!-- 门店实景 -->
          <view class="upload-item">
            <text class="upload-label">门店实景</text>
            <view class="upload-box" @click="uploadFile('shopImage')">
              <image 
                v-if="formData.shopImage" 
                :src="formData.shopImage" 
                class="preview-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="48" :color="isModified ? '#007AFF' : '#999'" />
              </view>
              <view 
                v-if="formData.shopImage" 
                class="delete-icon"
                @click.stop="formData.shopImage = ''"
              >
                <uni-icons type="close" size="20" color="#fff" />
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 保存按钮 -->
    <button 
      class="save-btn"
      :class="{ active: isModified }"
      @click="handleSubmit"
    >
      保存修改
    </button>
  </view>
</template>
<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import request from '../../utils/request'

// 表单数据结构
const formData = ref({
  principal: '',
  idNumber: '',
  phone: '',
  shopName: '',
  licenseNo: '',
  region: [],
  address: '',
  description: '',
  idCardFront: '',
  idCardBack: '',
  licenseImage: '',
  shopImage: ''
})

// 初始表单数据（用于对比是否修改）
const initialFormData = ref({ ...formData.value })

// 是否有修改
const isModified = ref(false)

// 监听表单数据变化
watch(
  formData,
  (newVal) => {
    isModified.value = JSON.stringify(newVal) !== JSON.stringify(initialFormData.value)
  },
  { deep: true }
)

// 使用 onMounted 获取路由参数
onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options

  if (options.data) {
    const data = JSON.parse(decodeURIComponent(options.data))
    console.log('接收到的数据:', data) // 打印传递过来的数据
    formData.value = {
		storeId:data.storeId,
	merchantId:data.merchantId,
      principal: data.name,
      idNumber: data.idCard,
      phone: data.phone,
      shopName: data.shopName,
      licenseNo: data.licenseNo,
      region: data.region ? data.region.split(' ') : [],
      address: data.address,
      description: data.description,
      idCardFront: data.idCardFront,
      idCardBack: data.idCardBack,
      licenseImage: data.licenseImage,
      shopImage: data.shopImage
    }
    // 更新初始数据
    initialFormData.value = { ...formData.value }
  } else {
    console.log('未接收到数据') // 如果没有数据，打印提示
  }
})

// 短信验证码
const smsText = ref('获取验证码')
const smsDisabled = ref(false)
let countdown = 60

// 获取验证码
const getSmsCode = () => {
  if (!/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    return uni.showToast({ title: '手机号格式错误', icon: 'none' })
  }
  
  smsDisabled.value = true
  const timer = setInterval(() => {
    countdown--
    smsText.value = `${countdown}s`
    
    if (countdown <= 0) {
      clearInterval(timer)
      smsText.value = '重新获取'
      smsDisabled.value = false
      countdown = 60
    }
  }, 1000)
}

// 图片上传
const uploadFile = async (field) => {
  try {
    const res = await uni.chooseMedia({
      count: 1,
      mediaType: ['image']
    })
    formData.value[field] = res.tempFiles[0].tempFilePath
  } catch (error) {
    console.log('上传取消', error)
  }
}

// 提交处理
const handleSubmit = () => {
  if (!isModified.value) {
    uni.showToast({ title: '未修改任何内容', icon: 'none' })
    return
  }

  // 打印修改的值
  const modifiedFields = {}
  for (const key in formData.value) {
    if (formData.value[key] !== initialFormData.value[key]) {
      modifiedFields[key] = formData.value[key]
    }
  }
  console.log('修改的值:', modifiedFields)

  // 构造 JSON 格式的提交数据
  const submitData = {
	  storeId: formData.value.storeId,
    storeName: formData.value.shopName,
    businessLicenseNo: formData.value.licenseNo,
    businessArea: formData.value.region.join(' '),
    address: formData.value.address,
    businessLicenseImage: formData.value.licenseImage,
    storeImage: formData.value.shopImage,
    description: formData.value.description,
    auditStatus: 1, // 设置为未审核
    merchant: {
			  merchantId:formData.merchantId,
      principal: formData.value.principal,
      idCard: formData.value.idNumber,
      phone: formData.value.phone,
      idCardFront: formData.value.idCardFront,
      idCardBack: formData.value.idCardBack
    }
  }

  // 打印提交的 JSON 数据
  console.log('提交的 JSON 数据:', JSON.stringify(submitData, null, 2))

  // 发送请求
  request({
    url: '/mstore/store',
    method: 'PUT', // 使用 PUT 方法
    headers: {
      'Content-Type': 'application/json' // 设置请求头为 JSON 格式
    },
    data: JSON.stringify(submitData) // 将数据转换为 JSON 字符串
	
  })
    .then((res) => {
      if (res.code === 200) {
        uni.showToast({ title: '保存成功', icon: 'success' })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } else {
        uni.showToast({ title: '保存失败，请重试', icon: 'none' })
      }
    })
    .catch((err) => {
      console.error('提交失败:', err)
      uni.showToast({ title: '网络错误，请重试', icon: 'none' })
    })
}
</script>

<style lang="scss" scoped>
.edit-container {
  background: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  margin: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.section-title {
  font-size: 32rpx;
  color: #333;
  padding-bottom: 24rpx;
  margin-bottom: 32rpx;
  border-bottom: 1rpx solid #eee;
}

.form-item {
  margin-bottom: 48rpx;
  
  .item-label {
    display: block;
    color: #666;
    font-size: 28rpx;
    margin-bottom: 16rpx;
  }
}

.form-input {
  height: 80rpx;
  padding: 0 24rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  
  &:focus {
    background: #fff;
    box-shadow: 0 0 0 2rpx #007AFF;
  }
}

.input-group {
  display: flex;
  gap: 16rpx;
  
  .sms-btn {
    width: 200rpx;
    height: 80rpx;
    line-height: 80rpx;
    background: #007AFF;
    color: #fff;
    border-radius: 8rpx;
    font-size: 24rpx;
    
    &[disabled] {
      background: #e0e0e0;
      color: #999;
    }
  }
}

.form-textarea {
  width: 100%;
  height: 200rpx;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.word-count {
  display: block;
  text-align: right;
  color: #999;
  font-size: 24rpx;
}

.upload-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32rpx;
}

.upload-item {
  .upload-label {
    display: block;
    color: #666;
    font-size: 24rpx;
    margin-bottom: 16rpx;
  }

  .upload-box {
    width: 100%;
    height: 240rpx;
    border: 2rpx dashed #007AFF;
    border-radius: 8rpx;
    position: relative;
    overflow: hidden;
    background: rgba(0,122,255,0.05);

    &.filled {
      border-color: transparent;
    }
  }

  .preview-image {
    width: 100%;
    height: 100%;
  }

  .upload-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .delete-icon {
    position: absolute;
    top: 8rpx;
    right: 8rpx;
    width: 40rpx;
    height: 40rpx;
    background: rgba(0,0,0,0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.save-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  line-height: 100rpx;
  background: #e0e0e0;
  color: #999;
  font-size: 32rpx;
  border-radius: 0;

  &.active {
    background: #007AFF;
    color: #fff;
  }

  &::after {
    border: none;
  }
}
</style>